package com.code.upload.controller;

import com.code.upload.utils.QiNiuUtil;
import com.code.upload.utils.Uploader;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;

/**
 * @author: liyufei
 * @date: 2018-05-02 22:51
 */
@Controller
@Slf4j
public class UploadController {

    @Autowired
    private QiNiuUtil qiNiuUtil;

    private static final HashMap<String, String> TypeMap = new HashMap<>();

    static {
        TypeMap.put("image", "gif,jpg,jpeg,png,bmp");
        TypeMap.put("flash", "swf,flv");
        TypeMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        TypeMap.put("file", "doc,docx,xls,xlsx,ppt,pptx,htm,html,txt,dwg,pdf");
    }

    /**
     * 去上传页面
     * @return
     */
    @GetMapping("/to-upload-page")
    public String toUploadPage() {
        return "upload";
    }

    /**
     * 文件上传
     * @param file
     */
    @PostMapping(value = "upload-file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        long fileSize = 2 * 1024 * 1024;
        // 文件大小大于限制
        if (file.getSize() > fileSize) {
            throw new RuntimeException("图片过大,请选择小于2M的图片");
        }
        // 获取文件名字 QQ图片20160224093916.jpg
        String originalFilename = file.getOriginalFilename();
        // 获取文件格式 jpg
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();

        if (!Arrays.asList(TypeMap.get("image").split(",")).contains(fileSuffix)) {
            throw new RuntimeException("上传图片格式不符合规范");
        }

        // 获取项目的真实路径 //  /mnt/img
        String realPath = "/mnt/img";
        // 获取文件类型 jpg
        String extension = FilenameUtils.getExtension(originalFilename).toLowerCase();
        // 获取 文件位置
        String filePath = Uploader.getQuickPathname(extension);
        // 拼接全路径
        File uploadedFile = new File(realPath + qiNiuUtil.createKey() + filePath);
        try {
            // 将文件保存到本地磁盘
            FileUtils.writeByteArrayToFile(uploadedFile, file.getBytes());
        } catch (IOException e) {
            log.error("文件上传到本地失败,文件:{},要上传的文件路径:{}", file, uploadedFile);
            e.printStackTrace();
        }

        String path = uploadedFile.getPath();
        if (!path.startsWith("/")) {
            path = File.separator + path;
        }
        // 生成 APP 端的手机缩略图, 使用 ImageIO 方式压缩图片
        String newPath = path.substring(0, path.lastIndexOf(".")) + "_appTh.png";


        String url = newPath.replaceAll("\\\\", "\\/");
        try {
            // 将文件上传到七牛云
            qiNiuUtil.upload(file.getInputStream(), url);
        } catch (IOException e) {
            log.error("文件获取流数据失败！源文件名：" + file.getOriginalFilename());
            e.printStackTrace();
        }
        return "upload";
    }
}
